package com.jbh.wanandroidkotlin.fragment

import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.android.material.tabs.TabLayout
import com.google.gson.Gson
import com.jbh.apilibrary.AppData
import com.jbh.apilibrary.bean.MessageListBean
import com.jbh.apilibrary.bean.MessageListResult
import com.jbh.apilibrary.i.ApiCallBack
import com.jbh.wanandroidkotlin.R
import com.jbh.wanandroidkotlin.activity.MessageActivity
import com.jbh.wanandroidkotlin.activity.TAB_1
import com.jbh.wanandroidkotlin.activity.TAB_2
import com.scwang.smartrefresh.layout.footer.ClassicsFooter
import com.scwang.smartrefresh.layout.header.ClassicsHeader
import com.yxjme.stateviewlayoutlibrary.StateViewLayout
import kotlinx.android.synthetic.main.activity_message.*
import kotlinx.android.synthetic.main.common_list_layout.*
import kotlinx.android.synthetic.main.fragment_message_list.*

private const val ARG_PARAM1 = "param1"

class MessageListFragment : Fragment() {
    /**
     * 记录上拉还是下拉
     */
    private var isPullRefresh = true
    /**
     * 当前页码
     */
    private var page = 1
    /**
     * 文章的总页数
     *
     */
    private var pageAll = 0;
    /**
     *
     * 列表数据
     */
    private var listContent  = mutableListOf<MessageListBean>()

    /**
     * 当前Tab
     */
    private var currentPosition = 0


    private var messageAdapter: MessageListAdapter?=null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            currentPosition = it.getInt(ARG_PARAM1)
        }
    }


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_message_list, container, false)
    }

    companion object {

        @JvmStatic
        fun newInstance(param1: Int) =
            MessageListFragment().apply {
                arguments = Bundle().apply {
                    putInt(ARG_PARAM1, param1)
                }
            }
    }



    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initList()
        mSmartRefreshLayout.autoRefresh()
    }




    private fun initList() {
        mSmartRefreshLayout.apply {
            setRefreshHeader(ClassicsHeader(activity))
            setRefreshFooter(ClassicsFooter(activity))
            setEnableRefresh(true)
            setEnableLoadMore(true)
            setOnRefreshListener { onRefresh() }
            setOnLoadMoreListener { onLoadMore() }
        }

        mRecyclerView.apply {
            val l = LinearLayoutManager(activity)
            l.orientation  = LinearLayoutManager.VERTICAL
            layoutManager =  l
            messageAdapter  = MessageListAdapter(listContent)
            adapter = messageAdapter

            val d= DividerItemDecoration(activity, RecyclerView.VERTICAL)
            val drawable= GradientDrawable()
            drawable.setColor(Color.GRAY)
            drawable.setSize(0,1)
            d.setDrawable(drawable)
            addItemDecoration(d)
        }
    }


    fun showEmpty(){
        mStateViewLayout.setMode(StateViewLayout.NO_DATA)
        mSmartRefreshLayout.visibility = View.GONE
    }

    fun hindEmpty(){
        mStateViewLayout.setMode(StateViewLayout.NONE)
        mSmartRefreshLayout.visibility = View.VISIBLE
    }


    /**
     * 下拉刷新
     *
     */
    private fun onRefresh() {
        isPullRefresh = true
        page = 1
        pageAll = 0
        listContent.clear()
        doTask()
    }



    /**
     * 上拉加载更多
     */
    private fun onLoadMore() {
        isPullRefresh = false
        page ++
        if (pageAll >= page){
            doTask()
        }else{
            mSmartRefreshLayout?.finishLoadMore(0, true, true)
        }
    }




    /**
     * 开始请求消息
     */


    private fun doTask(){
        when(currentPosition){
            TAB_1 ->{
                newMessageTask(page)
            }
            TAB_2 ->{
                readMessageTask(page)
            }
        }
    }






    private fun newMessageTask(page:Int){
        AppData.instance().newMessageTask(page,object : ApiCallBack<MessageListResult> {
            override fun success(data: MessageListResult) {
                println("[newMessageTask]->success=${Gson().toJson(data.datas)}")
                activity!!.runOnUiThread {
                    pageAll = data.pageCount
                    println("[indexArticleTask] - > success = $pageAll")
                    listContent.addAll(data.datas)
                    messageAdapter?.notifyDataSetChanged()
                    if (isPullRefresh) {
                        mSmartRefreshLayout?.finishRefresh()
                    } else {
                        mSmartRefreshLayout?.finishLoadMore(0, true, false)
                    }
                    hindEmpty()
                }
            }
            override fun error(error: String) {
                println("[newMessageTask]->error=$error")
                activity!!.runOnUiThread {
                    if (isPullRefresh) {
                        mSmartRefreshLayout?.finishRefresh()
                    } else {
                        mSmartRefreshLayout?.finishLoadMore(0, true, true)
                    }

                    showEmpty()
                }
            }
        })
    }


    private fun readMessageTask(page:Int){
        AppData.instance().readMessageTask(page,object : ApiCallBack<MessageListResult> {
            override fun success(data: MessageListResult) {
                println("[readMessageTask]->success=${Gson().toJson(data)}")
                activity!!. runOnUiThread {
                    pageAll = data.pageCount
                    println("[indexArticleTask] - > success = $pageAll")
                    listContent.addAll(data.datas)
                    messageAdapter?.notifyDataSetChanged()
                    if (isPullRefresh) {
                        mSmartRefreshLayout?.finishRefresh()
                    } else {
                        mSmartRefreshLayout?.finishLoadMore(0, true, false)
                    }
                    hindEmpty()

                }
            }


            override fun error(error: String) {
                println("[readMessageTask]->error=$error")
                activity!!.runOnUiThread {
                    if (isPullRefresh) {
                        mSmartRefreshLayout?.finishRefresh()
                    } else {
                        mSmartRefreshLayout?.finishLoadMore(0, true, true)
                    }
                    showEmpty()
                }
            }
        })
    }




    class MessageListAdapter(listContent:List<MessageListBean>) :
        BaseQuickAdapter<MessageListBean, BaseViewHolder>(R.layout.item_message_layout,listContent){
        override fun convert(helper: BaseViewHolder, item: MessageListBean) {
            helper.setText(R.id.tv_message,item.message)
                .setText(R.id.tv_time,item.niceDate)
                .setText(R.id.tv_tag,item.tag+"\n"+item.title)
        }
    }



    private fun messageCountTask(){
        AppData.instance().messageCountTask(object : ApiCallBack<Any> {
            override fun success(data: Any) {
                println("[messageCountTask]->success=${Gson().toJson(data)}")
            }

            override fun error(error: String) {
                println("[messageCountTask]->error=$error")
            }
        })
    }
}